package cn.junior_programmer.springsecurityjdbc.config;

import cn.junior_programmer.springsecurityjdbc.filter.CustomAuthenticationFilter;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author junior_programmer
 * <p>
 * EnableGlobalMethodSecurity   启用前置注解
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CustomSecurityConfiguration extends WebSecurityConfigurerAdapter {


    /**
     * spring security默认的登录接口，可自定义登录路径
     */
    private static final String DEFAULT_LOGIN_URL = "/login";


    /**
     * 定义密码加密bean,校验用户名密码需要用到
     *
     * @return 密码加密类
     */
    @Bean
    PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        final DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder());
        // 设置为false可以抛出UsernameNotFoundException 默认情况下会抛出BadCredentialsException
        provider.setHideUserNotFoundExceptions(false);
        return provider;
    }

    /**
     * DEFAULT_LOGIN_URL设置进白名单，其余接口全部需要登录后访问
     * <p>
     * formLogin() 配置表单登录的一些信息
     * loginProcessingUrl 设置登录接口的url
     * successHandler 登录成功使用自定义的事件处理器 CustomAuthenticationSuccessHandler
     * failureHandler 登陆失败使用自定义的事件处理器 CustomAuthenticationFailureHandler
     * <p>
     * exceptionHandling() 统一的异常处理信息
     * accessDeniedHandler 权限不足使用自定义的事件处理器 CustomAccessDeniedHandler
     * <p>
     * logout() 登出的配置信息
     * logoutSuccessHandler 登出成功使用自定义的事件处理器 CustomLogoutSuccessHandler
     *
     * @param http http
     * @throws Exception ex
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers(DEFAULT_LOGIN_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .formLogin()
                .loginProcessingUrl(DEFAULT_LOGIN_URL)
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new CustomAccessDeniedHandler())
                .and()
                .logout()
                .logoutSuccessHandler(new CustomLogoutSuccessHandler());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(authenticationProvider());
    }

    private void write(HttpServletResponse response, Map<String, Object> params) throws IOException {

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus((int) params.get("code"));


        response.getOutputStream().write(JSON.toJSONString(params).getBytes());

        response.getOutputStream().flush();
    }

    /**
     * 自定义权限不足处理事件
     */
    private class CustomAccessDeniedHandler implements AccessDeniedHandler {

        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

            Map<String, Object> params = new HashMap<>();

            params.put("code", HttpStatus.UNAUTHORIZED.value());
            params.put("error", accessDeniedException.getMessage());

            write(response, params);
        }
    }

    @Bean
    public CustomAuthenticationFilter customAuthenticationFilter() throws Exception {

        CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(DEFAULT_LOGIN_URL);

        customAuthenticationFilter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessHandler());
        customAuthenticationFilter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());
        customAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());

        return customAuthenticationFilter;
    }


    /**
     * 自定义登录成功触发事件
     */
    private class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            // 登出后返回json数据给前端显示
            Map<String, Object> params = new HashMap<>();

            params.put("code", HttpStatus.OK.value());

            write(response, params);

        }
    }


    /**
     * 自定义登录失败触发事件
     */
    private class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

            Map<String, Object> params = new HashMap<>();

            params.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
            params.put("error", exception.getMessage());

            write(response, params);
        }
    }


    /**
     * 自定义登出成功触发事件
     */
    private class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

        @Override
        public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            Map<String, Object> params = new HashMap<>();

            params.put("code", HttpStatus.OK.value());

            write(response, params);
        }
    }
}
